using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SharePoint;

namespace MessageBoard
{
	/// <summary>
	/// Summary description for User.
	/// </summary>
	public class User : Connection
	{
		private int _Id;
		private string _DisplayName;
		private string _DisplayImage;
		private string _Username;
		private string _Password;
		private int _TotalPosts;
		private Boolean _Loged;
		private DateTime _LatestHit;
        public SPWeb web;

		public User()
		{
		}

		public static User Get(System.Data.DataRow dr)
		{
			User user = new User();
			user.Id = int.Parse(dr["Id"].ToString());
            user.Username = dr["Username"].ToString();
            user.DisplayName = dr["DisplayName"].ToString();	
			user.DisplayImage = dr["DisplayImage"].ToString();			
			user.Password = dr["Password"].ToString();
			user.TotalPosts = int.Parse(dr["TotalPosts"].ToString());
			user.Loged = Convert.ToBoolean(dr["Loged"].ToString());
			user.LatestHit = Convert.ToDateTime(dr["LatestHit"].ToString());
			return user;
		}

		public static User Get(int id)
		{
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter("SELECT * FROM " + Connection.tblUser + " WHERE [Id] = @Id", DbConnection);
			getData.SelectCommand.Parameters.Add("@Id", id);
			getData.Fill(ds);
			if(ds.Tables[0].Rows.Count>0)
			{
				return Get(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}

		public static User Get(string userName)
		{
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter("SELECT * FROM " + Connection.tblUser + " WHERE [UserName] = @UserName", DbConnection);
			getData.SelectCommand.Parameters.Add("@UserName", userName);
			getData.Fill(ds);
			if(ds.Tables[0].Rows.Count>0)
			{
				return Get(ds.Tables[0].Rows[0]);
			}
			else
			{
				return null;
			}
		}

		public static System.Collections.ArrayList GetAll()
		{
			System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter("SELECT * FROM " + Connection.tblUser + "", DbConnection);
			getData.Fill(ds);
			foreach(System.Data.DataRow dr in ds.Tables[0].Rows)
			{
				arrayList.Add(Get(dr));
			}
			return arrayList;
		}

		/// <summary>
		/// Add the User in the database and set his permissions to 'User'
		/// </summary>
		public void Insert()
		{
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter(@"
			INSERT INTO " + Connection.tblUser + @" 
			([DisplayName], [DisplayImage], [Username], [Password],[TotalPosts], [Loged], [LatestHit])
			VALUES
			(@DisplayName, @DisplayImage, @Username, @Password, 0, 0, GetDate());
			SELECT @@identity as i", DbConnection);
			getData.SelectCommand.Parameters.Add("@DisplayName", DisplayName);
			getData.SelectCommand.Parameters.Add("@DisplayImage", DisplayImage);
			getData.SelectCommand.Parameters.Add("@Username", Username);
			getData.SelectCommand.Parameters.Add("@Password", Password);
			getData.Fill(ds);
			if(ds.Tables[0].Rows.Count>0)
			{
				Id = int.Parse(ds.Tables[0].Rows[0]["i"].ToString());
			}

			// add the user in Users UserGroup
			AddToUserGroup("User");
		}

		public void AddToUserGroup(string groupCode)
		{
			UserGroup usergroup = UserGroup.Get(groupCode);
			UsersInGroups usersInGroups = new UsersInGroups();
			usersInGroups.User = this;
			usersInGroups.UserGroup = usergroup;
			usersInGroups.Insert();
		}

		public void Update()
		{
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter(@"
			UPDATE " + Connection.tblUser + @" SET 
			[DisplayName] = @DisplayName,
			[DisplayImage] = @DisplayImage,
			[Username] = @Username,
			[Password] = @Password
			WHERE [Id] = @Id", DbConnection);
			getData.SelectCommand.Parameters.Add("@DisplayName", DisplayName);
			getData.SelectCommand.Parameters.Add("@DisplayImage", DisplayImage);
			getData.SelectCommand.Parameters.Add("@Username", Username);
			getData.SelectCommand.Parameters.Add("@Password", Password);
			getData.SelectCommand.Parameters.Add("@Id", Id);
			getData.Fill(ds);
		}

		public void MakeRequest()
		{
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter(@"
			UPDATE " + Connection.tblUser + @" SET 
			[LatestHit] = GetDate()
			WHERE [Id] = @Id", DbConnection);
			getData.SelectCommand.Parameters.Add("@Id", Id);
			getData.Fill(ds);
		}

		public void AddNewPost()
		{
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter(@"
			UPDATE " + Connection.tblUser + @" SET 
			[TotalPosts] = [TotalPosts] + 1
			WHERE [Id] = @Id", DbConnection);
			getData.SelectCommand.Parameters.Add("@Id", Id);
			getData.Fill(ds);
		}

		public void PostDeleted()
		{
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter(@"
			UPDATE " + Connection.tblUser + @" SET 
			[TotalPosts] = [TotalPosts] - 1
			WHERE [Id] = @Id", DbConnection);
			getData.SelectCommand.Parameters.Add("@Id", Id);
			getData.Fill(ds);
		}

		public void Login()
		{
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter(@"
			UPDATE " + Connection.tblUser + @" SET 
			[Loged] = 1,
			[LatestHit] = GetDate()
			WHERE [Id] = @Id", DbConnection);
			getData.SelectCommand.Parameters.Add("@Id", Id);
			getData.Fill(ds);
		}

		public void LogOut()
		{
			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter(@"
			UPDATE " + Connection.tblUser + @" SET 
			[Loged] = 0
			WHERE [Id] = @Id", DbConnection);
			getData.SelectCommand.Parameters.Add("@Id", Id);
			getData.Fill(ds);
		}

		public void Delete()
		{
			// Delete the related objects.
			DeletePosts();
			DeleteRelatedPermissions();
			DeleteFromUsersGroups();

			DataSet ds = new DataSet();
			SqlDataAdapter getData = new SqlDataAdapter(@"
			DELETE FROM " + Connection.tblUser + @" WHERE [Id] = @Id", DbConnection);
			getData.SelectCommand.Parameters.Add("@Id", Id);
			getData.Fill(ds);
		}

		/// <summary>
		/// Delete the user posts.
		/// </summary>
		private void DeletePosts()
		{
			foreach(Post post in Post.GetAll(this))
			{
				// check if the post is already deleted (if it is part of a deleted thread)
				if(post!=null)
					post.Delete();
			}			
		}

		/// <summary>
		/// Delete the user permissions.
		/// </summary>
		private void DeleteRelatedPermissions()
		{
			// Delete the user permissions.
			foreach(Role role in Role.GetAll(this))
			{
				role.Delete();
			}
		}

		/// <summary>
		/// Delete from the users groups.
		/// </summary>
		private void DeleteFromUsersGroups()
		{
			// Delete the user from the user group.
			foreach(UsersInGroups usersInGroups in UsersInGroups.GetAll(this))
			{
				usersInGroups.Delete();
			}
		}

		#region Properties
		/// <summary>
		/// The Id of the thread.
		/// </summary>
		public int Id
		{
			get
			{
				return _Id;
			}
			set
			{
				_Id = value;
			}
		}

		/// <summary>
		/// The DisplayName.
		/// </summary>
		public string DisplayName
		{
			get
			{
                if (String.IsNullOrEmpty(_DisplayName))
                {
                    if (web != null)
                    {
                        string[] names = new string[1];
                        names[0] = _Username;
                        _DisplayName = web.Users.GetCollection(names)[0].Name;
                        //_DisplayName = ;
                        //user.DisplayName = dr["DisplayName"].ToString();
                    }
                }
				return _DisplayName;
			}
			set
			{
				_DisplayName = value;
			}
		}

		/// <summary>
		/// The Display Image 50x50 px (imagename.gif).
		/// </summary>
		public string DisplayImage
		{
			get
			{
				return _DisplayImage;
			}
			set
			{
				_DisplayImage = value;
			}
		}

		/// <summary>
		/// The Username.
		/// </summary>
		public string Username
		{
			get
			{
				return _Username;
			}
			set
			{
				_Username = value;
			}
		}

		/// <summary>
		/// The Password.
		/// </summary>
		public string Password
		{
			get
			{
				return _Password;
			}
			set
			{
				_Password = value;
			}
		}

		/// <summary>
		/// Total Posts.
		/// </summary>
		public int TotalPosts
		{
			get
			{
				return _TotalPosts;
			}
			set
			{
				_TotalPosts = value;
			}
		}

		/// <summary>
		/// If the user Loged or not.
		/// </summary>
		public Boolean Loged
		{
			get
			{
				if(_LatestHit.AddMinutes(30)<DateTime.Now)
				{
					if(_Loged==true)
						this.LogOut();
					_Loged = false;									
				}
				else
				{
					if(_Loged==false)
						this.Login();
					_Loged = true;					
				}
				return _Loged;	
			}
			set
			{
				_Loged = value;
			}
		}

		/// <summary>
		/// The Latest Hit by the user.
		/// </summary>
		public DateTime LatestHit
		{
			get
			{
				return _LatestHit;
			}
			set
			{
				_LatestHit = value;
			}
		}
		
		#endregion
	}
}
